package com.mango.game.controller.pub;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.mango.game.common.JwtTokenProvider;
import com.mango.game.dtos.AdminLoginDTO;
import com.mango.game.dtos.LoginUserDTO;
import com.mango.game.dtos.ResponseDTO;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 管理员特殊接口
 * </p>
 *
 * @author Mango
 * @since 2025-02-24
 */
@RestController
public class LoginController {

    // 创建缓存实例
    private final Cache<String, String> loginCodeCache = Caffeine.newBuilder()
            .maximumSize(10000)
            .expireAfterWrite(5, TimeUnit.MINUTES)
            .build();

    private static final String username = "admin";

    private static final String password = "1234";

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @GetMapping("/login/code")
    public ResponseEntity<Object> code() {
        Captcha captcha = new SpecCaptcha(100, 40, 4);  // 生成验证码
        String uuid = UUID.randomUUID().toString(); // 生成编号
        loginCodeCache.put(uuid, captcha.text());
        return ResponseEntity.ok(new HashMap<String, String>() {{
            put("loginId", uuid);
            put("image", captcha.toBase64());
        }});
    }

    @PostMapping("/login/admin")
    public ResponseEntity<ResponseDTO> login(@RequestBody AdminLoginDTO dto) {
        if (dto.getLoginId() == null || dto.getLoginCode() == null){
            return ResponseDTO.failure("登录参数错误");
        }
        String loginCode = loginCodeCache.getIfPresent(dto.getLoginId());
        if (loginCode == null || !loginCode.equalsIgnoreCase(dto.getLoginCode())) {
            return ResponseDTO.failure("验证码错误");
        }

        if (!username.equalsIgnoreCase(dto.getUsername()) || !password.equalsIgnoreCase(dto.getPassword())) {
            return ResponseDTO.failure("帐号或者密码不对");
        }

        LoginUserDTO lu = new LoginUserDTO();
        lu.setAdmin(true);
        lu.setUsername(username);
        lu.setNickName(username);
        String token = jwtTokenProvider.generateToken(lu);

        return ResponseDTO.success("登录成功", token);
    }

}
